package club.itstudio.itouc.entity

import club.itstudio.itouc.core.exception.ITOUCException
import club.itstudio.itouc.core.util.*
import club.itstudio.itouc.util.Bean
import club.itstudio.itouc.util.Mysql
import club.itstudio.itouc.util.Redis
import javax.validation.constraints.Email
import javax.validation.constraints.Size

/**
 * 学生
 */
data class OUCStudent(
        var userCode: String = "",           // 学号
        var userName: String = "",           // 用户名
        var grade: String = "",              // 年级
        var specialtyCode: String = "",      // 专业代码
        var phone: String = "",              // 手机
        var email: String = "",               // 邮箱
        var wechat_openid: String = "",         // 微信openid
        var wechat_unionid: String = ""         // 微信unionid
) {
    /**
     * 持久化到Mysql和Redis
     */
    fun save(): OUCStudent{
        return this.also {
            it.saveMysql()
            it.saveRedis()
        }
    }
    fun saveRedis() = SpringContext.getBean(Redis::class.java).saveOUCStudent(this)
    private fun saveMysql() = SpringContext.getBean(Mysql::class.java).saveOUCStudent(this)

    /**
     * 更新数据
     */
    fun update(userCode: String = this.userCode,
               userName: String = this.userName,
               grade: String = this.grade,
               specialtyCode: String = this.specialtyCode,
               phone: String = this.phone,
               email: String = this.email) {
        this.userCode = userCode
        this.userName = userName
        this.grade = grade
        this.specialtyCode = specialtyCode
        this.phone = phone
        this.email = email
        this.save()
    }

    companion object{
        /**
         * 从本系统获取学生信息，不存在抛出Exception
         */
        fun getByUserCode(userCode: String): OUCStudent{
            return try {    // 从redis中取
                Bean.redis().getOUCStudent(userCode)
            }catch (e : ITOUCException) {
                // 从数据库取
               Bean.mysql().getOUCStudent(userCode).also {
                   it.saveRedis()
               }
            }
        }
    }
}

data class OUCStudentModel(
        @get:Size(min = 2, max = 8, message = "用户名长度为2-8位")
        var userName: String = "",           // 用户名
        @get:Size(min = 4, max = 4)
        var grade: String = "",              // 年级
        @get:Size(min = 4, max = 4)
        var specialty: String = "",          // 专业代码
        var phone: String = "",              // 手机
        @get:Email(message = "邮箱格式不正确")
        var email: String = ""               // 邮箱
)


